<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

const router = useRouter();

// 门锁设备数据
const locks = ref([
  {
    id: '1',
    name: '智能门锁-101',
    deviceId: 'LOCK001',
    status: 'online',
    location: '1号楼101房间',
    lastUpdate: '2024-01-19 15:30:00',
    lockStatus: 'locked',
    battery: 85,
    signal: 92,
    lastAccess: '2024-01-19 15:25:00',
    accessMethod: 'fingerprint',
    accessUser: '张三',
    failedAttempts: 0,
  },
  {
    id: '2',
    name: '智能门锁-102',
    deviceId: 'LOCK002',
    status: 'online',
    location: '1号楼102房间',
    lastUpdate: '2024-01-19 15:30:00',
    lockStatus: 'unlocked',
    battery: 92,
    signal: 88,
    lastAccess: '2024-01-19 15:20:00',
    accessMethod: 'password',
    accessUser: '李四',
    failedAttempts: 2,
  },
  {
    id: '3',
    name: '智能门锁-大厅',
    deviceId: 'LOCK003',
    status: 'warning',
    location: '1号楼大厅',
    lastUpdate: '2024-01-19 15:25:00',
    lockStatus: 'locked',
    battery: 45,
    signal: 65,
    lastAccess: '2024-01-19 15:15:00',
    accessMethod: 'card',
    accessUser: '王五',
    failedAttempts: 5,
  },
  {
    id: '4',
    name: '智能门锁-餐厅',
    deviceId: 'LOCK004',
    status: 'online',
    location: '1号楼餐厅',
    lastUpdate: '2024-01-19 15:30:00',
    lockStatus: 'locked',
    battery: 78,
    signal: 75,
    lastAccess: '2024-01-19 15:10:00',
    accessMethod: 'face',
    accessUser: '赵六',
    failedAttempts: 1,
  },
]);

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  lockStatus: '',
  location: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colors = {
    online: 'green',
    offline: 'red',
    warning: 'orange',
    error: 'red',
  };
  return colors[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const texts = {
    online: '在线',
    offline: '离线',
    warning: '异常',
    error: '故障',
  };
  return texts[status] || status;
};

// 获取锁状态颜色
const getLockStatusColor = (status: string) => {
  const colors = {
    locked: 'red',
    unlocked: 'green',
  };
  return colors[status] || 'default';
};

// 获取锁状态文本
const getLockStatusText = (status: string) => {
  const texts = {
    locked: '已锁定',
    unlocked: '未锁定',
  };
  return texts[status] || status;
};

// 获取访问方式文本
const getAccessMethodText = (method: string) => {
  const methods = {
    fingerprint: '指纹',
    password: '密码',
    card: '卡片',
    face: '人脸',
  };
  return methods[method] || method;
};

// 获取电池颜色
const getBatteryColor = (battery: number) => {
  return battery > 60 ? 'green' : battery > 30 ? 'orange' : 'red';
  battery60;
};

// 获取信号颜色
const getSignalColor = (signal: number) => {
  return signal >= 80
    ? 'green'
    : signal >= 60
      ? 'blue'
      : signal >= 40
        ? 'orange'
        : 'red';
};

// 表格列定义
const columns = [
  {
    title: '门锁名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '设备状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '锁状态',
    dataIndex: 'lockStatus',
    key: 'lockStatus',
    width: 100,
  },
  {
    title: '安装位置',
    dataIndex: 'location',
    key: 'location',
    width: 150,
  },
  {
    title: '电池电量',
    dataIndex: 'battery',
    key: 'battery',
    width: 100,
  },
  {
    title: '信号强度',
    dataIndex: 'signal',
    key: 'signal',
    width: 100,
  },
  {
    title: '最后访问',
    dataIndex: 'lastAccess',
    key: 'lastAccess',
    width: 150,
  },
  {
    title: '访问方式',
    dataIndex: 'accessMethod',
    key: 'accessMethod',
    width: 100,
  },
  {
    title: '访问用户',
    dataIndex: 'accessUser',
    key: 'accessUser',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
];

// 过滤后的数据
const filteredLocks = computed(() => {
  let result = locks.value;

  if (searchForm.name) {
    result = result.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase()),
    );
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.lockStatus) {
    result = result.filter((item) => item.lockStatus === searchForm.lockStatus);
  }

  if (searchForm.location) {
    result = result.filter((item) =>
      item.location.toLowerCase().includes(searchForm.location.toLowerCase()),
    );
  }

  return result;
});

// 门锁统计
const lockStatistics = computed(() => {
  const total = locks.value.length;
  const online = locks.value.filter((l) => l.status === 'online').length;
  const warning = locks.value.filter((l) => l.status === 'warning').length;
  const offline = locks.value.filter((l) => l.status === 'offline').length;
  const locked = locks.value.filter((l) => l.lockStatus === 'locked').length;
  const unlocked = locks.value.filter(
    (l) => l.lockStatus === 'unlocked',
  ).length;

  return { total, online, warning, offline, locked, unlocked };
});

// 查看设备详情
const viewDevice = (record: any) => {
  router.push(`/hotel/iot-devices/detail/${record.id}`);
};

// 控制设备
const controlDevice = (record: any) => {
  Modal.info({
    title: `设备控制 - ${record.name}`,
    width: 800,
    content: '设备控制功能开发中...',
  });
};

// 解锁门锁
const unlockLock = (record: any) => {
  Modal.confirm({
    title: '确认解锁',
    content: `确定要解锁门锁 "${record.name}" 吗？`,
    onOk: () => {
      message.success('门锁解锁成功');
      // 这里可以调用API进行实际解锁操作
    },
  });
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    status: '',
    lockStatus: '',
    location: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

onMounted(() => {
  pagination.total = filteredLocks.value.length;
});
</script>

<template>
  <div class="locks-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>门锁管理</h2>
      <Space>
        <Button @click="router.push('/hotel/iot-devices')">
          <IconifyIcon icon="ant-design:arrow-left-outlined" />
          返回设备列表
        </Button>
        <Button type="primary">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加门锁
        </Button>
      </Space>
    </div>

    <!-- 统计信息 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number total">{{ lockStatistics.total }}</div>
            <div class="stat-label">门锁总数</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number online">{{ lockStatistics.online }}</div>
            <div class="stat-label">在线门锁</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number warning">{{ lockStatistics.warning }}</div>
            <div class="stat-label">异常门锁</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number locked">{{ lockStatistics.locked }}</div>
            <div class="stat-label">已锁定</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number unlocked">
              {{ lockStatistics.unlocked }}
            </div>
            <div class="stat-label">未锁定</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">
              {{
                lockStatistics.total > 0
                  ? Math.round(
                      (lockStatistics.online / lockStatistics.total) * 100,
                    )
                  : 0
              }}%
            </div>
            <div class="stat-label">在线率</div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <Form.Item label="门锁名称">
          <Input
            v-model:value="searchForm.name"
            placeholder="请输入门锁名称"
            allow-clear
          />
        </Form.Item>
        <Form.Item label="设备状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <Select.Option value="online">在线</Select.Option>
            <Select.Option value="offline">离线</Select.Option>
            <Select.Option value="warning">异常</Select.Option>
            <Select.Option value="error">故障</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="锁状态">
          <Select
            v-model:value="searchForm.lockStatus"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <Select.Option value="locked">已锁定</Select.Option>
            <Select.Option value="unlocked">未锁定</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="安装位置">
          <Input
            v-model:value="searchForm.location"
            placeholder="请输入安装位置"
            allow-clear
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" @click="handleSearch">
              <IconifyIcon icon="ant-design:search-outlined" />
              搜索
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>

    <!-- 门锁列表 -->
    <Card title="门锁列表" class="list-card">
      <Table
        :columns="columns"
        :data-source="filteredLocks"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'lockStatus'">
            <Tag :color="getLockStatusColor(record.lockStatus)">
              {{ getLockStatusText(record.lockStatus) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'battery'">
            <Tag :color="getBatteryColor(record.battery)">
              {{ record.battery }}%
            </Tag>
          </template>
          <template v-else-if="column.key === 'signal'">
            <Tag :color="getSignalColor(record.signal)">
              {{ record.signal }}%
            </Tag>
          </template>
          <template v-else-if="column.key === 'accessMethod'">
            {{ getAccessMethodText(record.accessMethod) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDevice(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="controlDevice(record)">
                控制
              </Button>
              <Button
                v-if="record.lockStatus === 'locked'"
                type="link"
                size="small"
                @click="unlockLock(record)"
              >
                解锁
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style scoped>
.locks-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 16px;
}

.stat-number {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: bold;
}

.stat-number.total {
  color: #1890ff;
}

.stat-number.online {
  color: #52c41a;
}

.stat-number.warning {
  color: #faad14;
}

.stat-number.offline {
  color: #f5222d;
}

.stat-number.locked {
  color: #f5222d;
}

.stat-number.unlocked {
  color: #52c41a;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.search-card {
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.list-card {
  background: white;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
